package com.example.api.config.mybatisplus;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            log.info("start insert fill ....");
            this.strictInsertFill(metaObject, "createUser", () -> Integer.valueOf(String.valueOf(StpUtil.getLoginId())) , Integer.class);
            this.strictUpdateFill(metaObject, "updateUser", () -> Integer.valueOf(String.valueOf(StpUtil.getLoginId())), Integer.class);
        }
        catch (Exception e) {
            log.error(e.getMessage());
        }finally {
            this.strictInsertFill(metaObject, "createTime", () -> new Date(), Date.class);
            this.strictUpdateFill(metaObject, "updateTime", () -> new Date(), Date.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            log.info("start update fill ....");
            this.strictUpdateFill(metaObject, "updateUser", () -> Integer.valueOf(String.valueOf(StpUtil.getLoginId())), Integer.class);
        } catch (Exception e) {
            log.error(e.getMessage());
        }finally {
            this.strictUpdateFill(metaObject, "updateTime", () -> new Date(), Date.class);
        }
    }
}
